<?php
if (!defined('LZ_MODULE')) die('Access Denied');

$debug = true;

language('javascript');
$path = $_REQUEST['path'];
$action = $_REQUEST['action'];
if ($action == 'get_time')
{
	echo date(LANG_TIME);
	die;
}

$user=$_SESSION['user'];
$root='../';
if (!$user)
{
	if ($action != "savefile" )
		exitme("notice('".LOGIN_TIME_OUT."');window.location='login.php?module=phpdisk';","eval");
	else
		exitme1(PLEASE_LOG_IN);
}

$path = dealpath($path);
$action1 = $_COOKIE["action1"];
if (!is_dir($root))
{
	@mkdir($root) or die('can not mkdir '.$root);
}


if (!$path)
{
	exitme("notice('".NOT_PERMITTED."');opendir('$root');","eval");
}


include_once(LZ_BASEPATH.'library/file.php');

$lb = new Fileclass;

if (!$path && $_COOKIE["cpass"]) $path=$_COOKIE["cpass"];

if (!is_file($path) && !is_dir($path) && $action != "savefile") 
{
	$_s = "notice('".NOT_FOUND." $path');";
	if ($path != $root)
		$_s.= "opendir('$root');";
	exitme($_s,"eval");
}


if (is_dir($path) && substr($path,-1)!="/") $path.="/";


function name_sort($a, $b)
{
    if ($a['display_name'] == $b['display_name']) 
        return 0;
    else
		return ($a['display_name'] < $b['display_name']) ? -1 : 1;
}
/////////////output data////////////
if ($action=="list")
{
	if ($up=="yes")
	{
		$path=substr(0,strlen($path)-1,$path);
		$path=dirname($path)."/";
	}


	$lb->dir($path,$sdir,$sfile,$size);
	$re = array();
	!$config['last_modify_date_type'] && $config['last_modify_date_type'] = 'Y-m-d H:i';
	
	if ($_SESSION['login_user']['status'] == 'admin')
	{
		$sql = "SELECT * FROM lz_company WHERE 1=1";
		$arr = $db->get_all($sql);
		$display_name = array();
		foreach($arr as $company)
		{
			if($company['token'])
				$display_name[$company['token']] = $company['name'];
		}
	}
	

	foreach($sdir as $v)
	{
		//if (!preg_match('/^[a-zA-Z0-9,_=]+$/',$v)) continue;
		$arr = array(
			'type'=>'folder',
			'name'=>$v,
			'size'=>'',
			'path'=>$path.$v.'/',
			'display_name' => $v,//name_decode($v),
			'bytes' => 0,
			'ftype'=>FILE_TYPE_FOLDER,
			'modified'=>date($config['last_modify_date_type'],@filemtime($path.$v))
		);
		
		if ($display_name && $display_name[$v]) 
			$arr['display_name'] = $display_name[$v];
		$re[] = $arr;
	}
	usort($re,'name_sort');
	$re_all = $re;
	$re = array();
	for($i=0;$i<count($sfile);$i++)
	{
		$v = $sfile[$i];
		//if (!preg_match('/^[a-zA-Z0-9,_=]+$/',$v)) continue;
		$fext = strtoupper(getext($v));//strtoupper(getext(name_decode($sfile[$i])));
		
		!$fext && $fext = 'UNKNOWN';
		$ftype = defined('F_'.$fext)?constant('F_'.$fext):$fext;
		
		$arr = array(
			'type'=>'file',
			'name'=>$v,
			'path' => $path.$v,
			'display_name' => $v,//name_decode($v),
			'modified'=>date($config['last_modify_date_type'],@filemtime($path.$v)),
			'ftype'=>$ftype,
			'bytes'=>$size[$i],
			'size'=>dealsize($size[$i])
		);

		
		$re[] = $arr;
	}
	usort($re,'name_sort');
	array_add($re_all, $re,false);
	$re = $re_all;
	if (!is_readable($path) && count($re) < 1) $re = array( array('name'=>CAN_NOT_READ,'type'=>'folder','modified'=>''));
	$json = json_encode($re);
	exitme($json);
}
/////////////output data////////////
else if ($action=="search")
{
	$keyword = $_REQUEST['keyword'];
	$sre = $lb->search_file($path,$keyword);
	if (sizeof($sre['file'])==0&&sizeof($sre['dir'])==0) {
		exitme("notice('".SEARCHED_RESULT_0."')","eval");
	} else {
		!$config['last_modify_date_type'] && $config['last_modify_date_type'] = 'Y-m-d H:i';
		
		$lock_files = array();
		$arr = $lock->get_list( array('customer_id' => $_SESSION['login_user']['customer_id']) );
		foreach($arr as $l)
		{
			$lock_files[$l['file']] = array( 'user'=>$l['user'],'time'=>format_past_time($l['time']) );
		}
		$sdir = $sre['dir'];
		$sfile = $sre['file'];
		
		$re = array();
		foreach($sdir as $v)
		{
			if (substr($v,-1) == '/') $v = substr($v,0,-1);
			$orig_v = $v;
			$v = basename($v);
			if ($v == '.svn') continue;
			$arr = array(
				'type'=>'folder',
				'name'=>$v,
				'path'=>$orig_v,
				'size'=>'',
				'display_name' => name_decode($v),
				'bytes' => 0,
				'ftype'=>FILE_TYPE_FOLDER,
				'modified'=>date($config['last_modify_date_type'],@filemtime($orig_v))
			);
			$re[] = $arr;
		}
		
		
		for($i=0;$i<count($sfile);$i++)
		{
			$v = $sfile[$i];
			$orig_v = $v;
			$v = basename($v);
			$fext = strtoupper(getext(name_decode($v)));
			!$fext && $fext = 'UNKNOWN';
			$ftype = defined('F_'.$fext)?constant('F_'.$fext):$fext;
			
			$size = filesize($orig_v);
			$arr = array(
				'type'=>'file',
				'name'=>$v,
				'display_name' => name_decode($v),
				'modified'=>date($config['last_modify_date_type'],@filemtime($orig_v)),
				'ftype'=>$ftype,
				'path'=>$orig_v,
				'bytes'=>$size,
				'size'=>dealsize($size)
			);

			if ($lock_files[$orig_v])
			{
				$arr['locked'] = str_replace( 
					array(
						'{user}',
						'{time}'
						),
					array(
						$lock_files[$orig_v]['user'],
						$lock_files[$orig_v]['time']
						),
					FILE_LOCKED);
			}
			$re[] = $arr;
		}
		$json = array_to_json($re);
		exitme($json);
	}
}

/* done */
else if ($action == 'unlock')
{
	include_once(LZ_BASEPATH.'model/lock.php');
	$lock = new LZ_Lock;
	if ($lock->exists($path))
	{
		$lock->delete($path);
	}
	exitme('reloaddata();','eval');
}

/* done */
else if ($action == 'lock')
{
	include_once(LZ_BASEPATH.'model/lock.php');
	$lock = new LZ_Lock;
	if (!$lock->exists($path))
	{
		$_path = str_replace($config['document_root'],'',$path);
		if (preg_match('/([a-zA-Z0-9]{32})\/([a-zA-Z0-9]{32})/',$_path,$ms))
		{
			include_once('model/customer.php');
			$customer = new LZ_Customer;
			$arr = $customer->get_one_by_token($ms[2]);
			$customer_id = $arr['company_id'];
		}
		
		$cid = $_SESSION['login_user']['customer_id'];
		if (!$cid && $customer_id) $cid = $customer_id;
		$lock->add(array(
			'user' => $_SESSION['login_user']['email'],
			'customer_id' => $cid,
			'file' => $path,
			'time' => time()
		));
	}
	exitme('reloaddata();','eval');
}


/* done */
//change password
else if ($action == 'password')
{
	include_once(LZ_BASEPATH.'model/account.php');
	$account = new LZ_Account;
	$password = lz_encode($_POST['password']);
	if ($password)
	{
		if ($account->update($_SESSION['login_account']['account_id'],array('password'=>$password)))
		{
			exitme("notice('".PASSWORD_CHANGED."');window.movenotice = 1;setTimeout(close_notice,5000);","eval");
		}
		else
		{
			exitme("notice('Error');close_notice();","eval");
		}
	}
}


/* done */
///////////////delete files////////////////
else if ($action=="delete" && $user["delete"])
{
	$sfile = $_POST['sfile']; //urldecode1($_POST["sfile"]);
	$sdir = $_POST['sdir'];//urldecode1($_POST["sdir"]);
	echo $sfile." \n====\n===\n$sdir";
	
	$dn = 0; 
	$fn = 0; 
	$err = "";
	$logstr = '';
	$arr = explode("|",$sfile);

	foreach($arr as $v)
	{
		if ($v=="") continue;
		$filename = checkfilename($v);
		if ($lock->exists($filename))
		{
			//$err .= decode_path(str_replace($svn->co_path,'',$filename)). ' has been locked by '.$arr['user'].'<br />';
			$err .= decode_path(str_replace(str_replace("'", '', $svn->co_path),'',$filename)). 'を削除するには取置状態を解除してください。<br />';
			continue;
		} else {
			$svn->remove($filename);
			$fn++;
			$logstr .="delete $filename\n";
		}
	}

	$arr=explode("|",$sdir);

	include_once(LZ_BASEPATH.'model/lock.php');
	$lock = new LZ_Lock;
	
	foreach($arr as $v)
	{
		if ($v=="") continue;
		
		if ($arr = $lock->exists($v))
		{
			//$err .= decode_path(str_replace($svn->co_path,'',$arr['file'])). ' has been locked by '.$arr['user'].'<br />';
			$err .= decode_path(str_replace(str_replace("'", '', $svn->co_path),'',$arr['file'])). 'を削除するには取置状態を解除してください。<br />';
			continue;
		}
		
		$dirname=checkfilename($v);
		if ($handle = opendir($dirname)) 
		{
			while (false !== ($file = readdir($handle))) 
			{
				if ($file != "." && $file != ".." && $file != ".svn") 
				{
					$svn->remove($dirname.$file);
					$logstr.="delete [$dirname.$file]\n";
				}
			}
			closedir($handle);
		}


		$svn->remove($dirname);
		$logstr.="delete [$dirname]\n";
		$dn+=1;
	}
	$svn->commit();
	//if ($err) $err.='""';
	$str = '';
	$str.=($dn)?" $dn ".FOLDER:"";
	$str.=($fn)?" $fn ".FILE:"";	
	$str.=($fn+$dn == 0)?NOTHING_DELETED:DELETED;
	$str.=($err)?BR.BR.ERROR.BR.$err:"";
//var_dump($str);
//exit;
	exitme("notice('" . addslashes($str) . "');reloaddata();","eval");
}


/* done */
////revert 
else if ($action == 'revert')
{
	$sfile = $_POST['sfile'];
	$action1 = $_REQUEST['action1'];
	if ($action1 == 'revert_to')
	{
		//print_r($_REQUEST);
		$to_time = mktime($_REQUEST['hour'],$_REQUEST['minute'],$_REQUEST['second'],$_REQUEST['month'],$_REQUEST['day'],$_REQUEST['year']);

		if ($debug) echo "to_time=".date('Y-m-d H:i:s',$to_time);
	}
	elseif ($action1 == 'revert_latest') {
		// Nothing to do
	}
	else
	{
		$days = intval($_POST['days']);
		if ($debug) echo "days = $days\n";
		if ($days == 0 ) exitme("notice('Error');",'eval');
		$to_time = time() - $days*60*24*60;
	}
	
	$dn = 0; 
	$fn = 0; 
	$err = "";
	$logstr = '';
	$arr = explode("|",$sfile);

	foreach($arr as $v)
	{
		if ($v=="") continue;
		$filename=$v;
		$rs = $svn->get_log($filename);
		if ($debug)
		{
			foreach($rs as $_arr)
			{
				echo "\n\tr=".$_arr['r']." t=".date('d H:i:s',$_arr['time'])."\n";
			}
			echo "\nto_time = ".date('d H:i:s',$to_time)."\n";
		}
		$found = false;
		
		if ($action1 == 'revert_latest') {
			foreach($rs as $log) {
				if ($log['action'] == 'revert' || $log['action'] == 'latest') {
					continue;
				} else {
					$found_r = $log['r'];
					$found = true;
					$action_str = 'latest';
					break;
				}
			}
		}
		else if ($days != -1)
		{
			for($idx=0;$idx<count($rs);$idx++)
			{
				$r = $rs[$idx];
				if ($debug) echo "\n\t compare: r[time]=".$r['time']." to_time=$to_time\n";

				//if ($rs[$idx+1] && $r['time'] > $to_time )
				//if (($rs[$idx+1]['time'] == false || $rs[$idx+1]['time'] < $to_time) && $r['time'] > $to_time )
				if (($rs[$idx+1]['time'] && $rs[$idx+1]['time'] <= $to_time) && $r['time'] > $to_time )
				{

					if ($debug) echo "\n\n------\n";
					if ($debug) echo 'found:';
					if ($debug) print_r($rs[$idx+1]);
					$found_r = $rs[$idx+1]['r'];
					$found = true;
					$action_str = 'revert';
					break;
				}
			}
			if ($found==false) {
				exitme("notice('".TIME_NOT_EXIST."')",'eval');
			}
		}
		else
		{
			if ($debug) echo "now revert to the previous status\n";
			if (count($rs)>1)
			{
				$r = $rs[1];
				if ($debug) print_r($r);
				$found_r = $rs[1]['r'];
				$found = true;
				$action_str = 'revert';
			}
		}
		
		if ($l = $lock->exists($filename))
		{
			$msg = str_replace(array( '{user}','{time}') , array( $l['user'],format_past_time($l['time'])) ,RENAME_FILE_LOCKED);
			exitme("notice('$msg');",'eval');
		}
		
		if ($found)
		{
			$fn++;
			$svn->revert($filename,$found_r,$action_str);
		}
		
		if (!$found)
		{
			$err .= decode_path(str_replace($svn->orig_co,'',$filename)).' '.CAN_NOT_REVERT.BR;
		}
		
		$logstr .="revert $filename\n";
	}

	$str = '';
	$str.=($dn)?" $dn ".FOLDER:"";
	$str.=($fn)?" $fn ".FILE:"";	
	$str.=($fn+$dn == 0)?NOTHING_RECERTED:REVERTED;
	$str.=($err)?BR.BR.ERROR.BR.$err:"";
	exitme("notice('{$str}');close_revert();$('#revert_to').fadeOut(500);reloaddata();","eval");
	//exitme("notice('{$str}');reloaddata();","eval");
}

/* done */
//////////////new folder////////////////
else if ($action=="newdir" && $user["newdir"])
{
	$filename = checkfilename($path.name_encode($_REQUEST['name']));

	if (is_file($filename) || is_dir($filename)) exitme("notice('".EXISTS.":".addslashes($_REQUEST['name'])."')","eval");
	if ($svn->mkdir($filename))
	{
		exitme("notice('".NEW_FOLDER_DONE."');reloaddata();","eval");
	}
	else
	{
		exitme("notice('".NEW_FOLDER_ERROR."')","eval");
	}
}

/* done */
/////////////new file///////////
else if ($action=="newfile" && $user["newfile"])
{
	$filename = checkfilename($path.name_encode($_REQUEST['name']));
	if (is_file($filename) || is_dir($filename)) exitme("notice('".EXISTS."')","eval");
	if (@fclose(@fopen($filename,"a")))
	{
		$svn->add($filename);
		inlog("Make File,$filename");
		exitme("notice('".NEW_FILE_DONE."');reloaddata();","eval");
	}
	else
		exitme("notice('".NEW_FILE_ERROR."')","eval");
}

/* done */
//////////////rename//////////////
else if ($action=="rename" && $user["rename"] && !$newfile && !$newdir)
{
	$filename1 = $_REQUEST['filename'];
	if (substr($filename1,-1) == '/') $filename1 = substr($filename1,0,-1);
	$filename1 = checkfilename($filename1);
	$filename2 = name_encode($_REQUEST['new_name']);
	$filename2 = preg_replace('/\/[a-zA-Z,_=0-9]{1,}$/','/'.$filename2,$filename1);
	$filename2 = checkfilename($filename2);

	if (strlen($filename2) > strlen($svn->co_path)+240) {
		$msg = FILE_NAME_TOO_LONG;
		exitme("notice('{$msg}')",'eval');
	}

	echo "name1=$filename1\nname2=$filename2\n";
	if (is_file($filename2) || is_dir($filename2)) exitme("notice('".EXISTS.":".addslashes($_REQUEST['new_name'])."')","eval");
	
	if ($l = $lock->exists($filename1))
	{
		$msg = str_replace(array( '{user}','{time}') , array( $l['user'],format_past_time($l['time'])) ,RENAME_FILE_LOCKED);
		exitme("notice('$msg')",'eval');
	}
	
	if ($svn->rename($filename1,$filename2))
	{
		exitme("notice('".RENAME_DONE."');reloaddata();window.renaming=false;","eval");
	}
	else
	{
		exitme("notice('".RENAME_ERROR."');window.renaming=false;","eval");
	}
}

/* done */
///////////////paste/////////////////////////
else if ($action=="paste")
{
	$action1 = $_REQUEST['action1'];
	$cover = $_REQUEST['cover'];
//var_dump($_REQUEST);
//var_dump($action1);
//exit;

	if ($action1 == 'copy')
	{
		$customer_used_size = get_folder_size($user['root']);
		$customer_total = size_to_byte($config['default_customer_size']);
		if ($customer_used_size >= $customer_total)
		{
			die(SPACE_FULL);
		}
	}
	
	
	if ($action1 != "cut" && $action1 != "copy" && $action1 != 'move') exitme("notice('".CLIPBOARD_EMPTY."')","eval");
	$sfile = $_REQUEST['sfile'];
	$sdir = $_REQUEST['sdir'];
	
	$from_path = array();
	
	$sfile = explode("|",$sfile);
	$sdir = explode("|",$sdir);
	
	$cut = ($action1=="cut");
	$action2 = ($action1 == "cut")?CUT:COPY;
	$from = array();
	$to = array();
	$changed = false;
	for($i=0;$i<count($sdir);$i++)
	{
		if (!trim($sdir[$i])) continue;
		$from[] = $sdir[$i];
		$from_path[] = preg_replace('/\/[a-zA-Z0-9,_=]{1,}\/$/','/',$sdir[$i]);
		$to[] = get_available_filename($path.basename($sdir[$i]),$changed);
	}
	
	for($i=0;$i<count($sfile);$i++)
	{
		if (!trim($sfile[$i])) continue;
		$from[] = $sfile[$i];
		$from_path[] = preg_replace('/\/[a-zA-Z0-9,_=]{1,}$/','/',$sfile[$i]);
		$to[] = get_available_filename($path.basename($sfile[$i]),$changed);
	}

	
	$from_path = array_unique($from_path);

	$logstr = '';
	$err = '';
	$done = false;
	for($i=0;$i<count($from);$i++)
	{
		if ($action1 == 'copy')
		{
			if (!file_exists($to[$i]) && $svn->cp($from[$i],$to[$i]))
			{
				$logstr.= "copy $from[$i] $to[$i] \n";
				$done = true;
			}
			else
			{
				!$err && $err = COPY_FAILED.'\n';
				$err.= decode_path(str_replace($svn->co_path,'',$from[$i])).'\n';
			}
		}
		else if ($action1 == 'cut' || $action1 == 'move')
		{
			if ($l = $lock->exists($from[$i]))
			{
				$msg = str_replace(array( '{user}','{time}') , array( $l['user'],format_past_time($l['time'])) ,RENAME_FILE_LOCKED);
				exitme("notice('$msg')",'eval');
			}
			
//var_dump("foo");
//var_dump("FROM::".$from[$i]);
//var_dump("TO::".$to[$i]);
//exit;
			if (!file_exists($to[$i]) && $svn->rename($from[$i],$to[$i]))
			{
				$logstr.= "move $from[$i] $to[$i] \n";
				$done = true;
			}
			else
			{
				!$err && $err = CUT_FAILED.'\n';
				$err.= decode_path(str_replace($svn->co_path,'',$from[$i])).'\n';
			}
		}
	}
	
	if ($err) 
		$err = "\\nErrors:\\n$err"; 
	else
		$err = '';
	switch ($action1)
	{
		case 'cut':
			$msg = CUT_DONE;
			break;
		case 'move':
			$msg = MOVE_DONE;
			break;
		default:
			$msg = COPY_DONE;
	}
	
	if ($changed)
		$msg .= "\\n".FILE_NAME_CHANGED;
	if (!$done) {
		$eval="notice('{$err}');reloaddata('$path');";
	} else {
		$eval="notice('{$msg}');reloaddata('$path');";
	}
	if ($action1 == "cut" || $action1 == 'move')
	{
		foreach($from_path as $p)
			$eval.= "reloaddata('$p');";
		$eval.="window.copy_action1='';window.copy_sdir='';window.copy_sfile='';";
	}
	exitme($eval,"eval");
}

/* done */
else if ($action == 'log')
{
	$file = $_POST['file'];
	$arr = $svn->get_log($file);
	for($i=0;$i<count($arr);$i++)
	{
		$arr[$i]['time'] = date('Y-m-d H:i:s',$arr[$i]['time']);
		$arr[$i]['file'] = decode_path($arr[$i]['file']);
		if ($arr[$i]['action'] != 'revert') {
			$arr[$i]['other'] = decode_path($arr[$i]['other']);
		}
	}
	$json = array_to_json($arr);
	$log_path = decode_path(str_replace($_SESSION['co_path'],'',$file));
	exitme("var log_arr = $json;show_log(log_arr,\"$log_path\");",'eval');
}
else if ($action == 'delete_log')
{
	$keyword = $_REQUEST['keyword'];
	$arr = $svn->get_delete_log($keyword);
	if (!sizeof($arr)) {
		exitme("notice('".SEARCHED_RESULT_0."')","eval");
	} else {
		for($i=0;$i<count($arr);$i++)
		{
			$arr[$i]['r'] = $arr[$i]['r'];
			$arr[$i]['time'] = date('Y-m-d H:i:s',$arr[$i]['time']);
			$arr[$i]['encodedfile'] = $arr[$i]['file'];
			$arr[$i]['file'] = decode_path($arr[$i]['file']);
			if ($arr[$i]['action'] != 'revert')
				$arr[$i]['other'] = decode_path($arr[$i]['other']);
		}
		$json = array_to_json($arr);
		$log_path = decode_path(str_replace($_SESSION['co_path'],'',$file));
		exitme("var log_arr = $json;show_delete_log(log_arr,\"$log_path\");",'eval');
	}
}
else if ($action == 'revert_candidate_log')
{
	$filename = $_REQUEST['filename'];
	$revision= $_REQUEST['revision'];
	$arr = $svn->get_revert_candidate_log($filename, $revision);
	for($i=0;$i<count($arr);$i++)
	{
		$arr[$i]['r'] = $arr[$i]['r'];
		$arr[$i]['time'] = date('Y-m-d H:i:s',$arr[$i]['time']);
		$arr[$i]['encodedfile'] = $arr[$i]['file'];
		$arr[$i]['file'] = decode_path($arr[$i]['file']);
		if ($arr[$i]['action'] != 'revert')
			$arr[$i]['other'] = decode_path($arr[$i]['other']);
	}
	$json = array_to_json($arr);
	$log_path = decode_path(str_replace($_SESSION['co_path'],'',$file));
	exitme("var log_arr = $json;show_revert_candidate_log(log_arr,\"$log_path\");",'eval');
}
else if ($action == 'revert_candidate')
{
	$encodedfilepath = $_REQUEST['encodedfilepath'];
	$filename = $_REQUEST['filename'];
	$revision= $_REQUEST['revision'];
	$time= $_REQUEST['time'];

	if (strpos($encodedfilepath, "/")) {
		$encodedfilename = substr($encodedfilepath, strrpos($encodedfilepath, "/")+1);
	} else {
		$encodedfilename = $encodedfilepath;
	}

	$decoded_encodedfilename = name_decode($encodedfilename);

	$timestr = strtotime($time);
	$timestr = date("-Ymd-His", $timestr);

	/* PHP 5.1.6
	$tmppathinfo = pathinfo($decoded_encodedfilename);
	if ($tmppathinfo['extension']) {
		$encodednewfilename = name_encode(substr($tmppathinfo['basename'], 0, strpos($tmppathinfo['basename'], ".")).$timestr.'.'.$tmppathinfo['extension']);
	} else {
		$encodednewfilename = name_encode($decoded_encodedfilename.$timestr);
	}
	*/
	//AAA
	if (strpos($decoded_encodedfilename, '.')) {
		$basename = substr($decoded_encodedfilename, 0, strrpos($decoded_encodedfilename, '.'));
		$extension = substr($decoded_encodedfilename, strrpos($decoded_encodedfilename, '.')+1);
		//$encodednewfilename = name_encode(substr($basename, 0, strpos($basename, ".")).$timestr.'.'.$extension);
		$encodednewfilename = name_encode($basename.$timestr.'.'.$extension);
	} else {
		$encodednewfilename = name_encode($decoded_encodedfilename.$timestr);
	}

	if (is_file($path.$encodednewfilename) || is_dir($path.$encodednewfilename)) exitme("notice('".EXISTS.":".name_decode($encodednewfilename)."')","eval");

//var_dump("aa".$revision);
//exit;
	//$arr = $svn->revert_candidate($encodedfilepath, $revision, $encodednewfilename, $path);

	//削除時の状態に戻すように変更
	$prev_revision = $revision - 1;
	$arr = $svn->revert_candidate($encodedfilepath, $prev_revision, $encodednewfilename, $path);
	$done = true;
	//$log_path = decode_path(str_replace($_SESSION['co_path'],'',$file));
	exitme("notice('".NEW_FILE_DONE."');$('#delete_log').fadeOut(500);$('#revert_candidate_log').fadeOut(500);reloaddata();","eval");
}
else if ($action == 'noop')
{
	exit('ok');
}
else
{
	exitme("notice('".NOT_ALLOWED."')","eval");
}

function exitme($ss,$t=1,$charset=0)
{
	global $lang,$config;
	if (!$charset)
	{
		$charset = $config['host_charset'];
	}

	$ss = str_replace("\n"," \n ",$ss);
	$s = '+';
	if ($t === 1) $s.="OK";
	else if ($t === "eval") $s.="Eval";
	else $s.="Error";
	$s = $s."==?".$ss."?==";
	echo $s;
	die;
}

function checkfilename($file)
{
	if (!$file) return "";
	$file2 = dealpath($file);
	if ($file2 != $file) exitme('Path Error!');
	$newfile = preg_replace('/[^a-zA-Z0-9,_=\/]/','',$file);
	if ($newfile != $file) exitme('Name Error!');
	return $file;
}

function get_available_filename($filename,&$changed)
{
	$path = preg_replace('/\/[a-zA-Z0-9,_=]{1,}$/','/',$filename);
	$name = str_replace($path,'',$filename);
	$k = 0;
	$old_filename = $filename;
	while (file_exists($filename))
	{
		$_pre = "copy";
		if ($k>0) $_pre.= "($k)";
		$_pre.= " of ";
		$_name = name_encode($_pre.name_decode($name));
		$filename = $path.$_name;
		$k++;
	}
	if (!$changed) $changed = ($old_filename != $filename);
	return $filename;
}

function exitme1($s)
{
	global $lang;
	header("Content-type:TEXT/HTML;Charset=UTF-8");
	exit("<script language=javascript>alert('$s');window.close();</script>");
}

function checktype($filename)
{
	return true;
	global $user;
	$ftype = getext($filename);
}
?>
